<!DOCTYPE html>





<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="generator" content="Hexo 3.9.0">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.3.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.3.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.3.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '7.3.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    save_scroll: false,
    copycode: {"enable":false,"show_result":false,"style":null},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    }
  };
</script>

  <meta name="description" content="与 C++11 多线程相关的头文件C++11 新标准中引入了四个头文件来支持多线程编程，他们分别是 ,,,和。  ：该头文主要声明了两个类, std::atomic 和 std::atomic_flag，另外还声明了一套 C 风格的原子类型和与 C 兼容的原子操作的函数。  ：该头文件主要声明了 std::thread 类，另外 std::this_thread 命名空间也在该头文件中。  ：该头">
<meta name="keywords" content="c++11并发指南">
<meta property="og:type" content="article">
<meta property="og:title" content="c++11并发指南">
<meta property="og:url" content="http://yoursite.com/2019/06/19/c++11并发指南/index.html">
<meta property="og:site_name" content="XuQi&#39;s Blog">
<meta property="og:description" content="与 C++11 多线程相关的头文件C++11 新标准中引入了四个头文件来支持多线程编程，他们分别是 ,,,和。  ：该头文主要声明了两个类, std::atomic 和 std::atomic_flag，另外还声明了一套 C 风格的原子类型和与 C 兼容的原子操作的函数。  ：该头文件主要声明了 std::thread 类，另外 std::this_thread 命名空间也在该头文件中。  ：该头">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://yoursite.com/2019/06/19/c++11并发指南/1.png">
<meta property="og:image" content="http://yoursite.com/2019/06/19/c++11并发指南/2.png">
<meta property="og:updated_time" content="2019-10-20T13:23:23.045Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="c++11并发指南">
<meta name="twitter:description" content="与 C++11 多线程相关的头文件C++11 新标准中引入了四个头文件来支持多线程编程，他们分别是 ,,,和。  ：该头文主要声明了两个类, std::atomic 和 std::atomic_flag，另外还声明了一套 C 风格的原子类型和与 C 兼容的原子操作的函数。  ：该头文件主要声明了 std::thread 类，另外 std::this_thread 命名空间也在该头文件中。  ：该头">
<meta name="twitter:image" content="http://yoursite.com/2019/06/19/c++11并发指南/1.png">
  <link rel="canonical" href="http://yoursite.com/2019/06/19/c++11并发指南/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>c++11并发指南 | XuQi's Blog</title>
  








  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  <div class="container sidebar-position-left">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">XuQi's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
  </ul>

    

</nav>
</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content page-post-detail">
            

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/06/19/c++11并发指南/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="XuQi">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="XuQi's Blog">
    </span>
      <header class="post-header">

        
          <h1 class="post-title" itemprop="name headline">c++11并发指南

            
          </h1>
        

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2019-06-19 22:37:43" itemprop="dateCreated datePublished" datetime="2019-06-19T22:37:43+00:00">2019-06-19</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-10-20 13:23:23" itemprop="dateModified" datetime="2019-10-20T13:23:23+00:00">2019-10-20</time>
              </span>
            
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="与-C-11-多线程相关的头文件"><a href="#与-C-11-多线程相关的头文件" class="headerlink" title="与 C++11 多线程相关的头文件"></a>与 C++11 多线程相关的头文件</h3><p>C++11 新标准中引入了四个头文件来支持多线程编程，他们分别是<atomic> ,<thread>,<mutex>,<condition_variable>和<future>。</future></condition_variable></mutex></thread></atomic></p>
<ul>
<li><p><atomic>：该头文主要声明了两个类, std::atomic 和 std::atomic_flag，另外还声明了一套 C 风格的原子类型和与 C 兼容的原子操作的函数。</atomic></p>
</li>
<li><p><thread>：该头文件主要声明了 std::thread 类，另外 std::this_thread 命名空间也在该头文件中。</thread></p>
</li>
<li><p><mutex>：该头文件主要声明了与互斥量(mutex)相关的类，包括 std::mutex 系列类，std::lock_guard, std::unique_lock, 以及其他的类型和函数。</mutex></p>
</li>
<li><p><condition_variable>：该头文件主要声明了与条件变量相关的类，包括 std::condition_variable 和 std::condition_variable_any。</condition_variable></p>
</li>
<li><p><future>：该头文件主要声明了 std::promise, std::package_task 两个 Provider 类，以及 std::future 和 std::shared_future 两个 Future 类，另外还有一些与之相关的类型和函数，std::async() 函数就声明在此头文件中。</future></p>
<p><strong>Linux GCC4.6 环境下，编译时需要加 -pthread</strong></p>
</li>
</ul>
<h4 id="一句话话概括各个库的特征"><a href="#一句话话概括各个库的特征" class="headerlink" title="一句话话概括各个库的特征"></a>一句话话概括各个库的特征</h4><ul>
<li>std::thread创建就允许，允许后台运行</li>
<li>std::mutex 加锁解锁要配对</li>
<li>std::lock_guard 自动解锁</li>
<li>std::unique_lock 关联互斥体</li>
<li>std::promise 许诺给个未来</li>
<li>std::package_task 任务和返回值打包给线程</li>
<li>std::async  比package_task简单，自动创建线程</li>
<li>std::condition_variable 一般和unique_lock 一起用</li>
</ul>
<a id="more"></a>

<h3 id="c-内存模型"><a href="#c-内存模型" class="headerlink" title="c++ 内存模型"></a>c++ 内存模型</h3><p>假设存在两个共享变量a, b，初始值均为 0，两个线程运行不同的指令，如下表格所示，线程 1 设置 a 的值为 1，然后设置 R1 的值为 b，线程 2 设置 b 的值为 2，并设置 R2 的值为 a，请问在不加任何锁或者其他同步措施的情况下，R1，R2 的最终结果会是多少？</p>
<p><img src="/2019/06/19/c++11并发指南/1.png" alt></p>
<p>由于没有施加任何同步限制，两个线程将会交织执行，但交织执行时指令不发生重排，即线程 1 中的 a = 1 始终在 R1 = b 之前执行，而线程 2 中的 b = 2 始终在 R2 = a 之前执行 ，因此可能的执行序列共有 4!/(2!*2!) = 6 种：</p>
<p><img src="/2019/06/19/c++11并发指南/2.png" alt></p>
<h3 id="std-thread-线程详解"><a href="#std-thread-线程详解" class="headerlink" title="std::thread 线程详解"></a>std::thread 线程详解</h3><ul>
<li><p>(1). 默认构造函数，创建一个空的 thread 执行对象。</p>
</li>
<li><p>(2). 初始化构造函数，创建一个 thread对象，该 thread对象可被 joinable，新产生的线程会调用 fn 函数，该函数的参数由 args 给出。</p>
</li>
<li><p>(3). 拷贝构造函数(被禁用)，意味着 thread 不可被拷贝构造。</p>
</li>
<li><p>(4). move 构造函数，move 构造函数，调用成功之后 x 不代表任何 thread 执行对象。</p>
</li>
<li><p>注意：可被 joinable 的 thread 对象必须在他们销毁之前被主线程 join 或者将其设置为 detached.</p>
</li>
</ul>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;utility&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;thread&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;functional&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;atomic&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">f1</span><span class="params">(<span class="keyword">int</span> n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  	<span class="built_in">std</span>::this_thread::get_id()</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; ++i) &#123;</span><br><span class="line">        <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"Thread "</span> &lt;&lt; n &lt;&lt; <span class="string">" executing\n"</span>;</span><br><span class="line">        <span class="built_in">std</span>::this_thread::sleep_for(<span class="built_in">std</span>::chrono::milliseconds(<span class="number">10</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">f2</span><span class="params">(<span class="keyword">int</span>&amp; n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  	<span class="built_in">std</span>::this_thread::get_id()</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; ++i) &#123;</span><br><span class="line">        <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"Thread 2 executing\n"</span>;</span><br><span class="line">        ++n;</span><br><span class="line">        <span class="built_in">std</span>::this_thread::sleep_for(<span class="built_in">std</span>::chrono::milliseconds(<span class="number">10</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> n = <span class="number">0</span>;</span><br><span class="line">    <span class="built_in">std</span>::thread t1; <span class="comment">// t1 is not a thread</span></span><br><span class="line">    <span class="built_in">std</span>::<span class="function">thread <span class="title">t2</span><span class="params">(f1, n + <span class="number">1</span>)</span></span>; <span class="comment">// pass by value</span></span><br><span class="line">    <span class="built_in">std</span>::<span class="function">thread <span class="title">t3</span><span class="params">(f2, <span class="built_in">std</span>::ref(n))</span></span>; <span class="comment">// pass by reference</span></span><br><span class="line">    <span class="built_in">std</span>::<span class="function">thread <span class="title">t4</span><span class="params">(<span class="built_in">std</span>::move(t3))</span></span>; <span class="comment">// t4 is now running f2(). t3 is no longer a thread</span></span><br><span class="line">    t2.join();</span><br><span class="line">    t4.join();</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"Final value of n is "</span> &lt;&lt; n &lt;&lt; <span class="string">'\n'</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="std-mutex-互斥量详解"><a href="#std-mutex-互斥量详解" class="headerlink" title="std::mutex 互斥量详解"></a>std::mutex 互斥量详解</h3><p>std::mutex 对象提供了独占所有权的特性——即不支持递归地对 std::mutex 对象上锁，而 std::recursive_lock 则可以递归地对互斥量对象上锁。</p>
<ul>
<li>构造函数，std::mutex不允许拷贝构造，也不允许 move 拷贝，最初产生的 mutex 对象是处于 unlocked 状态的。</li>
<li>lock()，调用线程将锁住该互斥量。线程调用该函数会发生下面 3 种情况：<ul>
<li>如果该互斥量当前没有被锁住，则调用线程将该互斥量锁住，直到调用 unlock之前，该线程一直拥有该锁。</li>
<li>如果当前互斥量被其他线程锁住，<strong>则当前的调用线程被阻塞住。</strong></li>
<li>如果当前互斥量被当前调用线程锁住，则会产生死锁(deadlock)。</li>
</ul>
</li>
<li>unlock()， 解锁，释放对互斥量的所有权。</li>
<li>try_lock()，尝试锁住互斥量，如果互斥量被其他线程占有，<strong>则当前线程也不会被阻塞</strong>。线程调用该函数也会出现下面 3 种情况，<ul>
<li>如果当前互斥量没有被其他线程占有，则该线程锁住互斥量，直到该线程调用 unlock 释放互斥量。</li>
<li>如果当前互斥量被其他线程锁住，<strong>则当前调用线程返回 false，而并不会被阻塞掉。</strong></li>
<li>如果当前互斥量被当前调用线程锁住，则会产生死锁(deadlock)。</li>
</ul>
</li>
</ul>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;       // std::cout</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;thread&gt;         // std::thread</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;mutex&gt;          // std::mutex</span></span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">volatile</span> <span class="keyword">int</span> <span class="title">counter</span><span class="params">(<span class="number">0</span>)</span></span>; <span class="comment">// non-atomic counter</span></span><br><span class="line"><span class="built_in">std</span>::mutex mtx;           <span class="comment">// locks access to counter</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">attempt_10k_increases</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;<span class="number">10000</span>; ++i) &#123;</span><br><span class="line">        <span class="keyword">if</span> (mtx.try_lock()) &#123;   <span class="comment">// only increase if currently not locked:</span></span><br><span class="line">            ++counter;</span><br><span class="line">            mtx.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span> <span class="params">(<span class="keyword">int</span> argc, <span class="keyword">const</span> <span class="keyword">char</span>* argv[])</span> </span>&#123;</span><br><span class="line">    <span class="built_in">std</span>::thread threads[<span class="number">10</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;<span class="number">10</span>; ++i)</span><br><span class="line">        threads[i] = <span class="built_in">std</span>::thread(attempt_10k_increases);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">auto</span>&amp; th : threads) </span><br><span class="line">      th.join();</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; counter &lt;&lt; <span class="string">" successful increases of the counter.\n"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>其他Mutex 系列类(三种)</p>
</blockquote>
<ul>
<li><p>std::recursive_mutex，递归 Mutex 类，允许同一个线程对互斥量多次上锁（即递归上锁）</p>
</li>
<li><p>std::time_mutex，定时 Mutex 类。</p>
<ul>
<li>try_lock_for 函数接受一个时间范围，表示在这一段时间范围之内线程如果没有获得锁则被阻塞住（与 std::mutex 的 try_lock() 不同，try_lock 如果被调用时没有获得锁则直接返回 false），如果在此期间其他线程释放了锁，则该线程可以获得对互斥量的锁，如果超时（即在指定时间内还是没有获得锁），则返回 false。</li>
<li>try_lock_until 函数则接受一个时间点作为参数，在指定时间点未到来之前线程如果没有获得锁则被阻塞住，如果在此期间其他线程释放了锁，则该线程可以获得对互斥量的锁，如果超时（即在指定时间内还是没有获得锁），则返回 false。</li>
</ul>
</li>
<li><p>std::recursive_timed_mutex，定时递归 Mutex 类。</p>
</li>
</ul>
<h3 id="std-lock-guard-详解"><a href="#std-lock-guard-详解" class="headerlink" title="std::lock_guard 详解"></a>std::lock_guard 详解</h3><p>不需要管理，出范围自动解锁std::lock_guard，与 Mutex RAII() 资源获取就是初始化)相关，方便线程对互斥量上锁。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mutex m;</span><br><span class="line">m.lock();</span><br><span class="line">sharedVariable= getVar();</span><br><span class="line">m.unlock();</span><br></pre></td></tr></table></figure>

<p>如果忘记解锁，或者抛出异常会导致死锁。</p>
<p>使用std::lock_guard</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="built_in">std</span>::mutex m,</span><br><span class="line">  <span class="built_in">std</span>::lock_guard&lt;<span class="built_in">std</span>::mutex&gt; lockGuard(m); <span class="comment">//出了括号就解锁</span></span><br><span class="line">  sharedVariable= getVar();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="std-unique-lock-详解"><a href="#std-unique-lock-详解" class="headerlink" title="std::unique_lock 详解"></a>std::unique_lock 详解</h3><p>std::unique_lock，与 Mutex RAII (资源获取就是初始化)相关，方便线程对互斥量上锁，但提供了更好的上锁和解锁控制。</p>
<p>和lock_guard对比又增加以下功能：</p>
<ul>
<li>没有关联互斥体时创建 </li>
<li>没有锁定的互斥体时创建 </li>
<li>显式和重复设置或释放关联互斥锁 </li>
<li>移动互斥体 move </li>
<li>尝试锁定互斥体 </li>
<li>延迟锁定关联互斥体</li>
</ul>
<p>有些锁因为互斥体锁导致问题。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// deadlock.cpp</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;mutex&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;thread&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">CriticalData</span>&#123;</span></span><br><span class="line">  <span class="built_in">std</span>::mutex mut;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">deadLock</span><span class="params">(CriticalData&amp; a, CriticalData&amp; b)</span></span>&#123;</span><br><span class="line"></span><br><span class="line">  a.mut.lock();</span><br><span class="line">  <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"get the first mutex"</span> &lt;&lt; <span class="built_in">std</span>::<span class="built_in">endl</span>;</span><br><span class="line">  <span class="built_in">std</span>::this_thread::sleep_for(<span class="built_in">std</span>::chrono::milliseconds(<span class="number">1</span>));</span><br><span class="line">  b.mut.lock();</span><br><span class="line">  <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"get the second mutex"</span> &lt;&lt; <span class="built_in">std</span>::<span class="built_in">endl</span>;</span><br><span class="line">  <span class="comment">// do something with a and b</span></span><br><span class="line">  a.mut.unlock();</span><br><span class="line">  b.mut.unlock();</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line"></span><br><span class="line">  CriticalData c1;</span><br><span class="line">  CriticalData c2;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">std</span>::<span class="function">thread <span class="title">t1</span><span class="params">([&amp;]&#123;deadLock(c1,c2);&#125;)</span></span>; <span class="comment">// 两个线程互相锁</span></span><br><span class="line">  <span class="built_in">std</span>::<span class="function">thread <span class="title">t2</span><span class="params">([&amp;]&#123;deadLock(c2,c1);&#125;)</span></span>;</span><br><span class="line"></span><br><span class="line">  t1.join();</span><br><span class="line">  t2.join();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">CriticalData</span>&#123;</span></span><br><span class="line">  <span class="built_in">std</span>::mutex mut;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">deadLock</span><span class="params">(CriticalData&amp; a, CriticalData&amp; b)</span></span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">std</span>::unique_lock&lt;<span class="built_in">std</span>::mutex&gt;guard1(a.mut,<span class="built_in">std</span>::defer_lock);</span><br><span class="line">  <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"Thread: "</span> &lt;&lt; <span class="built_in">std</span>::this_thread::get_id() &lt;&lt; <span class="string">" first mutex"</span> &lt;&lt;  <span class="built_in">std</span>::<span class="built_in">endl</span>;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">std</span>::this_thread::sleep_for(<span class="built_in">std</span>::chrono::milliseconds(<span class="number">1</span>));</span><br><span class="line"></span><br><span class="line">  <span class="built_in">std</span>::unique_lock&lt;<span class="built_in">std</span>::mutex&gt;guard2(b.mut,<span class="built_in">std</span>::defer_lock);</span><br><span class="line">  <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"Thread:"</span> &lt;&lt; <span class="built_in">std</span>::this_thread::get_id() &lt;&lt; <span class="string">" second mutex"</span> &lt;&lt; <span class="built_in">std</span>::<span class="built_in">endl</span>;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"Thread:"</span> &lt;&lt; <span class="built_in">std</span>::this_thread::get_id() &lt;&lt; <span class="string">"get both mutex"</span> &lt;&lt; <span class="built_in">std</span>::<span class="built_in">endl</span>;</span><br><span class="line">  <span class="comment">// 如果用参数std::defer_lock调用std::unique_lock 的构造函数，锁不会自动锁定。 锁定操作是通过使用可变参数模板std::lock以原子方式执行锁定操作，</span></span><br><span class="line">  <span class="built_in">std</span>::lock(guard1,guard2);</span><br><span class="line">  <span class="comment">// do something with a and b</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="built_in">std</span>::<span class="built_in">endl</span>;</span><br><span class="line"></span><br><span class="line">  CriticalData c1;</span><br><span class="line">  CriticalData c2;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">std</span>::<span class="function">thread <span class="title">t1</span><span class="params">([&amp;]&#123;deadLock(c1,c2);&#125;)</span></span>;</span><br><span class="line">  <span class="built_in">std</span>::<span class="function">thread <span class="title">t2</span><span class="params">([&amp;]&#123;deadLock(c2,c1);&#125;)</span></span>;</span><br><span class="line"></span><br><span class="line">  t1.join();</span><br><span class="line">  t2.join();</span><br><span class="line"></span><br><span class="line">  <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="built_in">std</span>::<span class="built_in">endl</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>也可以反过来做。在第一步中，锁定互斥体，在第二步中用std::unique_lock处理资源的生命周期</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">std</span>::lock(a.mut, b.mut);</span><br><span class="line"><span class="built_in">std</span>::lock_guard&lt;<span class="built_in">std</span>::mutex&gt; guard1(a.mut, <span class="built_in">std</span>::adopt_lock);</span><br><span class="line"><span class="built_in">std</span>::lock_guard&lt;<span class="built_in">std</span>::mutex&gt; guard2(b.mut, <span class="built_in">std</span>::adopt_lock);</span><br></pre></td></tr></table></figure>

<h3 id="std-promise-详解"><a href="#std-promise-详解" class="headerlink" title="std::promise 详解"></a>std::promise 详解</h3><p><future> 头文件中包含了以下几个类和函数：</future></p>
<ul>
<li>Providers 类：std::promise, std::package_task</li>
<li>Futures 类：std::future, shared_future.</li>
<li>Providers 函数：std::async()</li>
<li>其他类型：std::future_error, std::future_errc, std::future_status, std::launch.</li>
</ul>
<p>promise 对象可以保存某一类型 T 的值，该值可被 future 对象读取（可能在另外一个线程中），因此 promise 也提供了一种线程同步的手段。在 promise 对象构造时可以和一个共享状态（通常是std::future）相关联，并可以在相关联的共享状态(std::future)上保存一个类型为 T 的值。</p>
<p>可以通过 get_future 来获取与该 promise 对象相关联的 future 对象，调用该函数之后，两个对象共享相同的共享状态(shared state)</p>
<ul>
<li>promise 对象是异步 Provider，它可以在某一时刻设置共享状态的值。</li>
<li>future 对象可以异步返回共享状态的值，或者在必要的情况下阻塞调用者并等待共享状态标志变为 ready，然后才能获取共享状态的值。</li>
</ul>
<p>下面以一个简单的例子来说明上述关系</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;       // std::cout</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;functional&gt;     // std::ref</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;thread&gt;         // std::thread</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;future&gt;         // std::promise, std::future</span></span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">print_int</span><span class="params">(<span class="built_in">std</span>::future&lt;<span class="keyword">int</span>&gt;&amp; fut)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> x = fut.get(); <span class="comment">// 获取共享状态的值,在set_value之前会阻塞</span></span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"value: "</span> &lt;&lt; x &lt;&lt; <span class="string">'\n'</span>; <span class="comment">// 打印 value: 10.</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span> <span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">std</span>::promise&lt;<span class="keyword">int</span>&gt; prom; <span class="comment">// 生成一个 std::promise&lt;int&gt; 对象.</span></span><br><span class="line">    <span class="built_in">std</span>::future&lt;<span class="keyword">int</span>&gt; fut = prom.get_future(); <span class="comment">// 和 future 关联.</span></span><br><span class="line">    <span class="built_in">std</span>::<span class="function">thread <span class="title">t</span><span class="params">(print_int, <span class="built_in">std</span>::ref(fut))</span></span>; <span class="comment">// 将 future 交给另外一个线程t.</span></span><br><span class="line">    prom.set_value(<span class="number">10</span>); <span class="comment">// 设置共享状态的值, 此处和线程t保持同步.</span></span><br><span class="line">    t.join();</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="std-packaged-task-详解"><a href="#std-packaged-task-详解" class="headerlink" title="std::packaged_task 详解"></a>std::packaged_task 详解</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;     // std::cout</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;future&gt;       // std::packaged_task, std::future</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;       // std::chrono::seconds</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;thread&gt;       // std::thread, std::this_thread::sleep_for</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">// count down taking a second for each value:</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">countdown</span> <span class="params">(<span class="keyword">int</span> from, <span class="keyword">int</span> to)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i=from; i!=to; --i) &#123;</span><br><span class="line">        <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; i &lt;&lt; <span class="string">'\n'</span>;</span><br><span class="line">        <span class="built_in">std</span>::this_thread::sleep_for(<span class="built_in">std</span>::chrono::seconds(<span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"Finished!\n"</span>;</span><br><span class="line">    <span class="keyword">return</span> from - to;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span> <span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">std</span>::packaged_task&lt;<span class="keyword">int</span>(<span class="keyword">int</span>,<span class="keyword">int</span>)&gt; task(countdown); <span class="comment">// 设置 packaged_task</span></span><br><span class="line">    <span class="built_in">std</span>::future&lt;<span class="keyword">int</span>&gt; ret = task.get_future(); <span class="comment">// 获得与 packaged_task 共享状态相关联的 future 对象.</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">std</span>::<span class="function">thread <span class="title">th</span><span class="params">(<span class="built_in">std</span>::move(task), <span class="number">5</span>, <span class="number">0</span>)</span></span>;   <span class="comment">//创建一个新线程完成计数任务.</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> value = ret.get();                    <span class="comment">// 等待任务完成并获取结果.</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"The countdown lasted for "</span> &lt;&lt; value &lt;&lt; <span class="string">" seconds.\n"</span>;</span><br><span class="line"></span><br><span class="line">    th.join();</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果</p>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">5</span></span><br><span class="line"><span class="number">4</span></span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="number">1</span></span><br><span class="line">Finished!</span><br><span class="line">The countdown lasted <span class="keyword">for</span> <span class="number">5</span> seconds.</span><br></pre></td></tr></table></figure>

<p>std::packaged_task 构造函数共有 5 中形式，不过拷贝构造已经被禁用了。下面简单地介绍一下上述几种构造函数的语义：</p>
<ol>
<li>默认构造函数，初始化一个空的共享状态，并且该 packaged_task 对象无包装任务。</li>
<li>初始化一个共享状态，并且被包装任务由参数 fn 指定。</li>
<li>带自定义内存分配器的构造函数，与默认构造函数类似，但是使用自定义分配器来分配共享状态。</li>
<li>拷贝构造函数，被禁用。</li>
<li>移动构造函数。</li>
</ol>
<p><strong>std::packaged_task::valid 介绍</strong></p>
<p>检查当前 packaged_task 是否和一个有效的共享状态相关联，对于由默认构造函数生成的 packaged_task 对象，该函数返回 false，除非中间进行了 move 赋值操作或者 swap 操作。</p>
<h3 id="std-async-详解"><a href="#std-async-详解" class="headerlink" title="std::async 详解"></a>std::async 详解</h3><p>c++11还提供了异步接口std::async，通过这个异步接口可以很方便的获取线程函数的执行结果。std::async会自动创建一个线程去调用线程函数，它返回一个std::future，这个future中存储了线程函数返回的结果，当我们需要线程函数的结果时，直接从future中获取，非常方便。</p>
<p>std::async是为了让用户的少费点脑子的。大概的工作过程是这样的：std::async先将异步操作用std::packaged_task包装起来，然后将异步操作的结果放到std::promise中，这个过程就是创造未来的过程。外面再通过future.get/wait来获取这个未来的结果，怎么样，std::async真的是来帮忙的吧，你不用再想到底该怎么用std::future、std::promise和std::packaged_task了，std::async已经帮你搞定一切了！</p>
<p>std::async的原型async(std::launch::async | std::launch::deferred, f, args…)，第一个参数是线程的创建策略，有两种策略，默认的策略是立即创建线程</p>
<ul>
<li>std::launch::async：在调用async就开始创建线程。</li>
<li>std::launch::deferred：延迟加载方式创建线程。调用async时不创建线程，直到调用了future的get或者wait时才创建线程。</li>
</ul>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// future example</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;             // std::cout</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;future&gt;               // std::async, std::future</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;               // std::chrono::milliseconds</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">// a non-optimized way of checking for prime numbers:</span></span><br><span class="line"><span class="keyword">bool</span></span><br><span class="line">is_prime(<span class="keyword">int</span> x)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">2</span>; i &lt; x; ++i)</span><br><span class="line">        <span class="keyword">if</span> (x % i == <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span></span><br><span class="line">main()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">// call function asynchronously:</span></span><br><span class="line">    <span class="built_in">std</span>::future &lt; <span class="keyword">bool</span> &gt; fut = <span class="built_in">std</span>::async(is_prime, <span class="number">444444443</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// do something while waiting for function to set future:</span></span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"checking, please wait"</span>;</span><br><span class="line">    <span class="built_in">std</span>::chrono::<span class="function">milliseconds <span class="title">span</span><span class="params">(<span class="number">100</span>)</span></span>;</span><br><span class="line">    <span class="keyword">while</span> (fut.wait_for(span) == <span class="built_in">std</span>::future_status::timeout)</span><br><span class="line">        <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">'.'</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">bool</span> x = fut.get();         <span class="comment">// retrieve return value</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"\n444444443 "</span> &lt;&lt; (x ? <span class="string">"is"</span> : <span class="string">"is not"</span>) &lt;&lt; <span class="string">" prime.\n"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">std</span>::future&lt;<span class="keyword">int</span>&gt; future = <span class="built_in">std</span>::async(<span class="built_in">std</span>::launch::async, []()&#123; </span><br><span class="line">        <span class="built_in">std</span>::this_thread::sleep_for(<span class="built_in">std</span>::chrono::seconds(<span class="number">3</span>));</span><br><span class="line">        <span class="keyword">return</span> <span class="number">8</span>;  </span><br><span class="line">    &#125;); </span><br><span class="line"> </span><br><span class="line"><span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"waiting...\n"</span>;</span><br><span class="line"><span class="built_in">std</span>::future_status status;</span><br><span class="line"><span class="keyword">do</span> &#123;</span><br><span class="line">  status = future.wait_for(<span class="built_in">std</span>::chrono::seconds(<span class="number">1</span>));</span><br><span class="line">  <span class="keyword">if</span> (status == <span class="built_in">std</span>::future_status::deferred) &#123;</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"deferred\n"</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (status == <span class="built_in">std</span>::future_status::timeout) &#123;</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"timeout\n"</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (status == <span class="built_in">std</span>::future_status::ready) &#123;</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"ready!\n"</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125; <span class="keyword">while</span> (status != <span class="built_in">std</span>::future_status::ready); </span><br><span class="line"></span><br><span class="line"><span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"result is "</span> &lt;&lt; future.get() &lt;&lt; <span class="string">'\n'</span>;</span><br></pre></td></tr></table></figure>

<h3 id="std-condition-variable-条件变量详解"><a href="#std-condition-variable-条件变量详解" class="headerlink" title="std::condition_variable 条件变量详解"></a>std::condition_variable 条件变量详解</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;                // std::cout</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;thread&gt;                // std::thread</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;mutex&gt;                // std::mutex, std::unique_lock</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;condition_variable&gt;    // std::condition_variable</span></span></span><br><span class="line"></span><br><span class="line"><span class="built_in">std</span>::mutex mtx;              <span class="comment">// 全局互斥锁.</span></span><br><span class="line"><span class="built_in">std</span>::condition_variable cv;  <span class="comment">// 全局条件变量.</span></span><br><span class="line"><span class="keyword">bool</span> ready = <span class="literal">false</span>;          <span class="comment">// 全局标志位.</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">do_print_id</span><span class="params">(<span class="keyword">int</span> id)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">std</span>::unique_lock &lt;<span class="built_in">std</span>::mutex&gt; lck(mtx); <span class="comment">// 因为使用的同一把锁，所以其实不起效果</span></span><br><span class="line">    <span class="keyword">while</span> (!ready) <span class="comment">// 如果标志位不为 true, 则等待...</span></span><br><span class="line">        cv.wait(lck); <span class="comment">// 当前线程被阻塞, 当全局标志位变为 true 之后,</span></span><br><span class="line">    <span class="comment">// 线程被唤醒, 继续往下执行打印线程编号id.</span></span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"thread "</span> &lt;&lt; id &lt;&lt; <span class="string">'\n'</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">go</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">std</span>::unique_lock &lt;<span class="built_in">std</span>::mutex&gt; lck(mtx);</span><br><span class="line">    ready = <span class="literal">true</span>; <span class="comment">// 设置全局标志位为 true.</span></span><br><span class="line">    cv.notify_all(); <span class="comment">// 唤醒所有线程.</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">std</span>::thread threads[<span class="number">10</span>];    <span class="comment">// spawn 10 threads:</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; ++i)</span><br><span class="line">        threads[i] = <span class="built_in">std</span>::thread(do_print_id, i);</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"10 threads ready to race...\n"</span>;</span><br><span class="line">    go(); <span class="comment">// go!</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">auto</span> &amp; th:threads)</span><br><span class="line">        th.join();</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p><strong>std::condition_variable::wait()</strong> </p>
<p>std::condition_variable 提供了两种 wait() 函数。当前线程调用 wait() 后将被阻塞(此时当前线程应该获得了锁（mutex），不妨设获得锁 lck)，直到另外某个线程调用 notify_* 唤醒了当前线程。</p>
<p>在线程被阻塞时，该函数会自动调用 <code>lck.unlock() 释放锁，使得其他被阻塞在锁竞争上的线程得以继续执行。</code>另外，一旦当前线程获得通知(notified，通常是另外某个线程调用 notify_* 唤醒了当前线程)，wait() 函数也是自动调用 lck.lock()，使得 lck 的状态和 wait 函数被调用时相同。</p>
</li>
<li><p><strong>std::condition_variable::wait_for()</strong></p>
<p>wait_for 可以指定一个时间段，在当前线程收到通知或者指定的时间 rel_time 超时之前，该线程都会处于阻塞状态。而一旦超时或者收到了其他线程的通知，wait_for 返回，剩下的处理步骤和 wait() 类似。</p>
<p>另外，wait_for 的重载版本（<strong>predicte(2)</strong>）的最后一个参数 pred 表示 wait_for 的预测条件，只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程，并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞，因此相当于如下代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">return</span> wait_until (lck, chrono::steady_clock::now() + rel_time, <span class="built_in">std</span>::move(pred));</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>std::condition_variable::wait_until</strong></p>
<p>wait_until 可以指定一个时间点，在当前线程收到通知或者指定的时间点 abs_time 超时之前，该线程都会处于阻塞状态。而一旦超时或者收到了其他线程的通知，wait_until 返回，剩下的处理步骤和 wait_until() 类似。</p>
<p>另外，wait_until 的重载版本（<strong>predicte(2)</strong>）的最后一个参数 pred 表示 wait_until 的预测条件，只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程，并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞，因此相当于如下代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> (!pred())</span><br><span class="line">  <span class="keyword">if</span> ( wait_until(lck,abs_time) == cv_status::timeout)</span><br><span class="line">    <span class="keyword">return</span> pred();</span><br><span class="line"><span class="keyword">return</span> <span class="literal">true</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>std::condition_variable::notify_one()</strong></p>
<p>唤醒某个等待(wait)线程。如果当前没有等待线程，则该函数什么也不做，如果同时存在多个等待线程，则唤醒某个线程是不确定的(unspecified)。</p>
</li>
</ul>
<ul>
<li><p><strong>std::condition_variable::notify_all()</strong> </p>
<p>唤醒所有的等待(wait)线程。如果当前没有等待线程，则该函数什么也不做。</p>
</li>
</ul>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;                // std::cout</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;thread&gt;                // std::thread, std::this_thread::yield</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;mutex&gt;                // std::mutex, std::unique_lock</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;condition_variable&gt;    // std::condition_variable</span></span></span><br><span class="line"></span><br><span class="line"><span class="built_in">std</span>::mutex mtx;</span><br><span class="line"><span class="built_in">std</span>::condition_variable cv;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> cargo = <span class="number">0</span>;</span><br><span class="line"><span class="function"><span class="keyword">bool</span> <span class="title">shipment_available</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> cargo != <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 消费者线程.</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">consume</span><span class="params">(<span class="keyword">int</span> n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; ++i) &#123;</span><br><span class="line">        <span class="built_in">std</span>::unique_lock &lt;<span class="built_in">std</span>::mutex&gt; lck(mtx);</span><br><span class="line">        cv.wait(lck, shipment_available);</span><br><span class="line">        <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; cargo &lt;&lt; <span class="string">'\n'</span>;</span><br><span class="line">        cargo = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">std</span>::<span class="function">thread <span class="title">consumer_thread</span><span class="params">(consume, <span class="number">10</span>)</span></span>; <span class="comment">// 消费者线程.</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 主线程为生产者线程, 生产 10 个物品.</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; ++i) &#123;</span><br><span class="line">        <span class="keyword">while</span> (shipment_available())</span><br><span class="line">            <span class="built_in">std</span>::this_thread::yield();</span><br><span class="line">        <span class="built_in">std</span>::unique_lock &lt;<span class="built_in">std</span>::mutex&gt; lck(mtx);</span><br><span class="line">        cargo = i + <span class="number">1</span>;</span><br><span class="line">        cv.notify_one();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    consumer_thread.join();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="std-atomic-flag-原子类型详解"><a href="#std-atomic-flag-原子类型详解" class="headerlink" title="std::atomic_flag 原子类型详解"></a>std::atomic_flag 原子类型详解</h3><p>atomic_flag 一种简单的原子布尔类型，只支持两种操作，test-and-set 和 clear。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;                // std::cout</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;atomic&gt;                // std::atomic_flag</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;thread&gt;                // std::thread</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;vector&gt;                // std::vector</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sstream&gt;                // std::stringstream</span></span></span><br><span class="line"></span><br><span class="line"><span class="built_in">std</span>::atomic_flag lock_stream = ATOMIC_FLAG_INIT;</span><br><span class="line"><span class="built_in">std</span>::<span class="built_in">stringstream</span> stream;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">append_number</span><span class="params">(<span class="keyword">int</span> x)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (lock_stream.test_and_set()) &#123;</span><br><span class="line">    &#125;</span><br><span class="line">    stream &lt;&lt; <span class="string">"thread #"</span> &lt;&lt; x &lt;&lt; <span class="string">'\n'</span>;</span><br><span class="line">    lock_stream.clear();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">vector</span> &lt; <span class="built_in">std</span>::thread &gt; threads;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= <span class="number">10</span>; ++i)</span><br><span class="line">        threads.push_back(<span class="built_in">std</span>::thread(append_number, i));</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">auto</span> &amp; th:threads)</span><br><span class="line">        th.join();</span><br><span class="line"></span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; stream.str() &lt;&lt; <span class="built_in">std</span>::<span class="built_in">endl</span>;;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="std-atomic-详解"><a href="#std-atomic-详解" class="headerlink" title="std::atomic 详解"></a>std::atomic 详解</h3><p>std::atomic 是模板类，一个模板类型为 T 的原子对象中封装了一个类型为 T 的值。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>&gt; <span class="title">struct</span> <span class="title">atomic</span>;</span></span><br><span class="line"></span><br><span class="line"># 在atomic中对基本类型有定义</span><br><span class="line"><span class="keyword">typedef</span> atomic&lt;<span class="keyword">bool</span>&gt;               <span class="keyword">atomic_bool</span>;</span><br><span class="line"><span class="keyword">typedef</span> atomic&lt;<span class="keyword">char</span>&gt;               <span class="keyword">atomic_char</span>;</span><br><span class="line"><span class="keyword">typedef</span> atomic&lt;<span class="keyword">signed</span> <span class="keyword">char</span>&gt;        <span class="keyword">atomic_schar</span>;</span><br><span class="line"><span class="keyword">typedef</span> atomic&lt;<span class="keyword">unsigned</span> <span class="keyword">char</span>&gt;      <span class="keyword">atomic_uchar</span>;</span><br><span class="line"><span class="keyword">typedef</span> atomic&lt;<span class="keyword">short</span>&gt;              <span class="keyword">atomic_short</span>;</span><br><span class="line"><span class="keyword">typedef</span> atomic&lt;<span class="keyword">unsigned</span> <span class="keyword">short</span>&gt;     <span class="keyword">atomic_ushort</span>;</span><br></pre></td></tr></table></figure>

<p>原子类型对象的主要特点就是从不同线程访问不会导致数据竞争(data race)。因此从不同线程访问某个原子对象是良性 (<em>well-defined</em>) 行为，而通常对于非原子类型而言，并发访问某个对象（如果不做任何同步操作）会导致未定义 (<em>undifined</em>) 行为发生。</p>
<p>std::atomic 是模板类，一个模板类型为 T 的原子对象中封装了一个类型为 T 的值。本文&lt;<strong>std::atomic 基本介绍</strong>&gt;一节中也提到了 std::atomic 类模板除了基本类型以外，还针对整形和指针类型做了特化。 特化的 std::atomic 类型支持更多的操作，如 fetch_add, fetch_sub, fetch_and 等。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;             // std::cout</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;atomic&gt;               // std::atomic</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;thread&gt;               // std::thread, std::this_thread::yield</span></span></span><br><span class="line"> </span><br><span class="line"><span class="built_in">std</span>::atomic &lt;<span class="keyword">int</span>&gt; foo = <span class="number">0</span>;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">set_foo</span><span class="params">(<span class="keyword">int</span> x)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    foo = x; <span class="comment">// 调用 std::atomic::operator=().</span></span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">print_foo</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (foo == <span class="number">0</span>) &#123; <span class="comment">// wait while foo == 0</span></span><br><span class="line">        <span class="built_in">std</span>::this_thread::yield();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"foo: "</span> &lt;&lt; foo &lt;&lt; <span class="string">'\n'</span>;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">std</span>::<span class="function">thread <span class="title">first</span><span class="params">(print_foo)</span></span>;</span><br><span class="line">    <span class="built_in">std</span>::<span class="function">thread <span class="title">second</span><span class="params">(set_foo, <span class="number">10</span>)</span></span>;</span><br><span class="line">    first.join();</span><br><span class="line">    second.join();</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="线程池的实现"><a href="#线程池的实现" class="headerlink" title="线程池的实现"></a>线程池的实现</h3><p>.h</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">// Created by xuqi on 2019-06-17.</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> THREADPOOL_H</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> THREADPOOL_H</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;vector&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;queue&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;memory&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;thread&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;mutex&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;condition_variable&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;future&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;functional&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdexcept&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">//#define C14</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ThreadPool</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    ThreadPool(<span class="keyword">size_t</span>);</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifdef</span> C14</span></span><br><span class="line">    <span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">F</span>,<span class="title">class</span>... <span class="title">Args</span>&gt;</span></span><br><span class="line"><span class="class">    <span class="title">auto</span> <span class="title">enqueue</span>(<span class="title">F</span>&amp;&amp; <span class="title">f</span>,<span class="title">Args</span>&amp;&amp;... <span class="title">args</span>);</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">else</span></span></span><br><span class="line">    <span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">F</span>, <span class="title">class</span>... <span class="title">Args</span>&gt;</span></span><br><span class="line"><span class="class">    <span class="title">auto</span> <span class="title">enqueue</span>(<span class="title">F</span>&amp;&amp; <span class="title">f</span>, <span class="title">Args</span>&amp;&amp;... <span class="title">args</span>)</span></span><br><span class="line"><span class="class">    -&gt; <span class="title">std</span>:</span>:future&lt;<span class="keyword">typename</span> <span class="built_in">std</span>::result_of&lt;F(Args...)&gt;::type&gt;;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">    ~ThreadPool();</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    <span class="comment">// 线程池</span></span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">vector</span>&lt; <span class="built_in">std</span>::thread &gt; workers;</span><br><span class="line">    <span class="comment">// 任务队列</span></span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">queue</span>&lt; <span class="built_in">std</span>::function&lt;<span class="keyword">void</span>()&gt; &gt; tasks;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// synchronization同步</span></span><br><span class="line">    <span class="built_in">std</span>::mutex queue_mutex;</span><br><span class="line">    <span class="built_in">std</span>::condition_variable condition;</span><br><span class="line">    <span class="keyword">bool</span> stop;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span> <span class="comment">//THREADPOOL_H</span></span></span><br></pre></td></tr></table></figure>

<p>.cpp</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">// Created by xuqi on 2019-06-17.</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"ThreadPool.h"</span></span></span><br><span class="line">ThreadPool::ThreadPool(<span class="keyword">size_t</span> threads)</span><br><span class="line">    : stop(<span class="literal">false</span>)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">// 创建n个线程，每个线程等待是否有新的task, 或者线程stop（要终止）</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">size_t</span> i = <span class="number">0</span>; i &lt; threads; ++i) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 构造并插入vector最后</span></span><br><span class="line">        workers.emplace_back(</span><br><span class="line">            [<span class="keyword">this</span>]</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">for</span> (;;)<span class="comment">// 轮询</span></span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="built_in">std</span>::function&lt;<span class="keyword">void</span>()&gt; task; <span class="comment">// 只有取Task的时候是锁的</span></span><br><span class="line">                    &#123;</span><br><span class="line">                        <span class="comment">// 获取同步锁</span></span><br><span class="line">                        <span class="built_in">std</span>::unique_lock&lt;<span class="built_in">std</span>::mutex&gt; lock(<span class="keyword">this</span>-&gt;queue_mutex);</span><br><span class="line">                        <span class="comment">// 线程会一直阻塞，直到有新的task，或者是线程要退出</span></span><br><span class="line">                        <span class="keyword">this</span>-&gt;condition.wait(lock,</span><br><span class="line">                                             [<span class="keyword">this</span>]</span><br><span class="line">                                             &#123; <span class="keyword">return</span> <span class="keyword">this</span>-&gt;stop || !<span class="keyword">this</span>-&gt;tasks.empty(); &#125;);</span><br><span class="line">                        <span class="comment">// 线程退出</span></span><br><span class="line">                        <span class="keyword">if</span> (<span class="keyword">this</span>-&gt;stop &amp;&amp; <span class="keyword">this</span>-&gt;tasks.empty())</span><br><span class="line">                            <span class="keyword">return</span>;</span><br><span class="line">                        <span class="comment">// 将task取出</span></span><br><span class="line">                        task = <span class="built_in">std</span>::move(<span class="keyword">this</span>-&gt;tasks.front());</span><br><span class="line">                        <span class="comment">// 队列中移除以及取出的task</span></span><br><span class="line">                        <span class="keyword">this</span>-&gt;tasks.pop();</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">// 执行task,完了则进入下一次循环</span></span><br><span class="line">                    task();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        );</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// add new work item to the pool</span></span><br><span class="line"><span class="comment">// 将队列压入线程池,其中f是要执行的函数， args是多有的参数</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifdef</span> C14</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">F</span>, <span class="title">class</span>... <span class="title">Args</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">auto</span> <span class="title">ThreadPool</span>:</span>:enqueue(F &amp;&amp;f, Args &amp;&amp;... args)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">nullptr</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">else</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">F</span>, <span class="title">class</span>... <span class="title">Args</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">auto</span> <span class="title">ThreadPool</span>:</span>:enqueue(F&amp;&amp; f, Args&amp;&amp;... args) <span class="comment">// 右值引用</span></span><br><span class="line">-&gt; <span class="built_in">std</span>::future&lt;<span class="keyword">typename</span> <span class="built_in">std</span>::result_of&lt;F(Args...)&gt;::type&gt; <span class="comment">// 拖尾类型返回</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">// 返回的结果的类型，当然可以根据实际的需要去掉这个(gcc4.7的c++11不支持)</span></span><br><span class="line">    <span class="keyword">using</span> return_type = <span class="keyword">typename</span> <span class="built_in">std</span>::result_of&lt;F(Args...)&gt;::type;</span><br><span class="line">    <span class="comment">// 将函数handle与参数绑定</span></span><br><span class="line">    <span class="keyword">auto</span> task = <span class="built_in">std</span>::make_shared&lt;<span class="built_in">std</span>::packaged_task&lt;return_type()&gt; &gt;(</span><br><span class="line">        <span class="built_in">std</span>::bind(<span class="built_in">std</span>::forward&lt;F&gt;(f), <span class="built_in">std</span>::forward&lt;Args&gt;(args)...)</span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">    <span class="comment">//after finishing the task, then get result by res.get() (mainly used in the invoked function)</span></span><br><span class="line">    <span class="built_in">std</span>::future&lt;return_type&gt; res = task-&gt;get_future();</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// 压入队列需要线程安全，因此需要先获取锁</span></span><br><span class="line">        <span class="built_in">std</span>::unique_lock&lt;<span class="built_in">std</span>::mutex&gt; lock(queue_mutex);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// don't allow enqueueing after stopping the pool</span></span><br><span class="line">        <span class="keyword">if</span> (stop)</span><br><span class="line">            <span class="keyword">throw</span> <span class="built_in">std</span>::runtime_error(<span class="string">"enqueue on stopped ThreadPool"</span>);</span><br><span class="line">        <span class="comment">// 任务压入队列</span></span><br><span class="line">        tasks.emplace([task]()</span><br><span class="line">                      &#123; (*task)(); &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 添加了新的task，因此条件变量通知其他线程可以获取task执行</span></span><br><span class="line">    condition.notify_one();</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line"></span><br><span class="line">ThreadPool::~ThreadPool()</span><br><span class="line">&#123;</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">std</span>::unique_lock&lt;<span class="built_in">std</span>::mutex&gt; lock(queue_mutex);</span><br><span class="line">        stop = <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 通知所有在等待锁的线程</span></span><br><span class="line">    condition.notify_all();</span><br><span class="line">    <span class="comment">// 等待所有的线程任务执行完成退出</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="built_in">std</span>::thread &amp;worker: workers)</span><br><span class="line">        worker.join();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用示例：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">ThreadPool <span class="title">tp</span><span class="params">(<span class="number">5</span>)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//线程执行结果的返回</span></span><br><span class="line"><span class="built_in">std</span>::<span class="built_in">vector</span>&lt;<span class="built_in">std</span>::future&lt;<span class="built_in">std</span>::<span class="built_in">string</span>&gt;&gt; vecStr;</span><br><span class="line"><span class="comment">// 下载对应的url链接，没有返回值</span></span><br><span class="line">tp.enqueue(dummy_download, <span class="string">"www.baidu.jpg"</span>);</span><br><span class="line">tp.enqueue(dummy_download, <span class="string">"www.yy.jpg"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//数据库根据id查询user name</span></span><br><span class="line">vecStr.emplace_back(tp.enqueue(get_user_name, <span class="number">101</span>));</span><br><span class="line">vecStr.emplace_back(tp.enqueue(get_user_name, <span class="number">102</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">//输出线程返回的值，实际中可以不要</span></span><br><span class="line"><span class="built_in">std</span>::future&lt;<span class="keyword">void</span>&gt; res1 = <span class="built_in">std</span>::async(<span class="built_in">std</span>::launch::async, [&amp;vecStr]()&#123;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">auto</span> &amp;&amp;ret:vecStr) &#123;</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span>&lt;&lt;<span class="string">"get user: "</span>&lt;&lt;ret.get();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">std</span>::<span class="built_in">cout</span>&lt;&lt;<span class="built_in">std</span>::<span class="built_in">endl</span>;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>


    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/c-11并发指南/" rel="tag"># c++11并发指南</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2019/06/17/线程池/" rel="next" title="线程池">
                  <i class="fa fa-chevron-left"></i> 线程池
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2019/06/24/socket编程/" rel="prev" title="socket编程">
                  socket编程 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">

          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">XuQi</p>
  <div class="site-description motion-element" itemprop="description"></div>
</div>
  <nav class="site-state motion-element">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">44</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
        
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">30</span>
        <span class="site-state-item-name">标签</span>
        
      </div>
    
  </nav>



        </div>
      </div>
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#与-C-11-多线程相关的头文件"><span class="nav-number">1.</span> <span class="nav-text">与 C++11 多线程相关的头文件</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#一句话话概括各个库的特征"><span class="nav-number">1.1.</span> <span class="nav-text">一句话话概括各个库的特征</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#c-内存模型"><span class="nav-number">2.</span> <span class="nav-text">c++ 内存模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#std-thread-线程详解"><span class="nav-number">3.</span> <span class="nav-text">std::thread 线程详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#std-mutex-互斥量详解"><span class="nav-number">4.</span> <span class="nav-text">std::mutex 互斥量详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#std-lock-guard-详解"><span class="nav-number">5.</span> <span class="nav-text">std::lock_guard 详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#std-unique-lock-详解"><span class="nav-number">6.</span> <span class="nav-text">std::unique_lock 详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#std-promise-详解"><span class="nav-number">7.</span> <span class="nav-text">std::promise 详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#std-packaged-task-详解"><span class="nav-number">8.</span> <span class="nav-text">std::packaged_task 详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#std-async-详解"><span class="nav-number">9.</span> <span class="nav-text">std::async 详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#std-condition-variable-条件变量详解"><span class="nav-number">10.</span> <span class="nav-text">std::condition_variable 条件变量详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#std-atomic-flag-原子类型详解"><span class="nav-number">11.</span> <span class="nav-text">std::atomic_flag 原子类型详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#std-atomic-详解"><span class="nav-number">12.</span> <span class="nav-text">std::atomic 详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程池的实现"><span class="nav-number">13.</span> <span class="nav-text">线程池的实现</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">XuQi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> v7.3.0</div>

        








        
      </div>
    </footer>
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
      </div>

    

  </div>

  
  <script src="/lib/jquery/index.js?v=3.4.1"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

<script src="/js/utils.js?v=7.3.0"></script>
  <script src="/js/motion.js?v=7.3.0"></script>


  <script src="/js/schemes/muse.js?v=7.3.0"></script>


<script src="/js/next-boot.js?v=7.3.0"></script>




  




























  

  

  


  
  <script src="/js/scrollspy.js?v=7.3.0"></script>
<script src="/js/post-details.js?v=7.3.0"></script>


</body>
</html>
